package kablamo;

import java.io.IOException;

import kablamo.SensorRequestData.SensorDataObject;

import org.glassfish.grizzly.Grizzly;
import org.glassfish.grizzly.filterchain.BaseFilter;
import org.glassfish.grizzly.filterchain.FilterChainContext;
import org.glassfish.grizzly.filterchain.NextAction;
import org.glassfish.grizzly.attributes.Attribute;

import org.glassfish.grizzly.Buffer;
import org.glassfish.grizzly.Connection;



public class DataResponseFilter extends BaseFilter {
	
	public int counter = 0;
	
	@Override
	public NextAction handleRead(FilterChainContext ctx)
		throws IOException {
		
		Object message = ctx.getMessage();
		if(message instanceof SensorRequestInit) {
			final SensorRequestInit sensorRequestInit = (SensorRequestInit) message;
			
			boolean authSuccess = true;
			
			SensorCodecStateTransitionEvent e = new SensorCodecStateTransitionEvent();
			e.success = authSuccess;
			ctx.notifyDownstream(e);
			
			
			
			System.out.println("AccessKey: " + sensorRequestInit.accessKey);
			System.out.println("DeviceKey: " + sensorRequestInit.deviceKey);
			System.out.println("TimeStamp: " + sensorRequestInit.timeStamp);
		} 
		else if(message instanceof SensorRequestData) {
			System.out.println("Data records: ");
			for(SensorDataObject sensorDataObject : ((SensorRequestData) message).dataElements) {
				counter++;
				System.out.println("Record:" + sensorDataObject.sequenceNumber + " Sid:" + sensorDataObject.sensorId + 
						" Value:" + sensorDataObject.sensorData + " timeStamp:" + 
						((SensorRequestData) message).masterTimeStamp + sensorDataObject.timeStampDelta);
			}
		}
		System.out.println("Counter: " + this.counter);
		System.out.println("We made it here...");
		
		return ctx.getStopAction();
		
	}
}
